<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>流向分析</title>
    <script src="/js/ll.js"></script>
    <link href="/css/font.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        accent: '#0ea5e9',
                        neutral: '#f1f5f9',
                        'neutral-dark': '#334155',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .table-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .table-fixed-layout th,
            .table-fixed-layout td {
                border: 1px solid #ddd;  /* 细线边框 */
                padding: 8px;
            }

            .hover-scale {
                transition: all 0.2s ease-in-out;
            }
            .hover-scale:hover {
                box-shadow: 0 6px 25px rgba(0, 0, 0, 0.12);
            }
            .sortable-header {
                cursor: pointer;
                user-select: none;
                transition: all 0.2s ease;
            }
            .sortable-header:hover {
                background-color: #f3f4f6;
                transform: none;
            }
            .sort-icon {
                margin-left: 4px;
                opacity: 0.5;
            }
            .sort-icon.active {
                opacity: 1;
                color: #3b82f6;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<div class="container mx-auto px-4 py-8 max-w-7xl">
<!--    <header class="mb-8">-->
<!--        <h1 class="text-[clamp(1.8rem,3vw,2.5rem)] font-bold text-neutral-dark mb-2 flex items-center">-->
<!--            <i class="fa fa-line-chart text-primary mr-3"></i>概念资金流向分析-->
<!--&lt;!&ndash;        </h1>&ndash;&gt;-->
<!--&lt;!&ndash;        <h2 class="text-neutral-dark mb-2 flex items-center">&ndash;&gt;-->
<!--            <a href="/" class="btn btn-outline-primary btn-sm float-right">&nbsp;&nbsp;&nbsp;返回主页</a>|-->
<!--            <a href="/limitup/search" class="btn btn-outline-primary btn-sm float-right">涨停查询</a>|-->
<!--            <a href="/analysis" class="btn btn-outline-primary btn-sm float-right">数据分析</a>-->
<!--        </h2>-->

<!--            <nav>-->
<!--                <ul class="flex space-x-6">-->
<!--                    <li><a href="/" class="text-primary font-medium hover:text-primary/80 transition-colors">首页</a></li>-->
<!--                    <li><a href="/analysis" class="text-gray-600 hover:text-primary transition-colors">数据分析</a></li>-->
<!--                    <li><a href="/limitup/search" class="text-gray-600 hover:text-primary transition-colors">ZT分析</a></li>-->
<!--                    <li><a href="/gainian" class="text-gray-600 hover:text-primary transition-colors">板块资金</a></li>-->
<!--                </ul>-->
<!--            </nav>-->
<!--&lt;!&ndash;        <p class="text-gray-600 text-lg">按概念代码统计的资金流向汇总数据</p>&ndash;&gt;-->
<!--    </header>-->

    <header class="bg-white shadow-sm sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-line-chart text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">概念资金流向分析</h1>
            </div>
            <button id="exportBtn" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center">
                <i class="fa fa-download mr-2"></i>导出表格
            </button>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="/" class="text-primary font-medium hover:text-primary/80 transition-colors">首页</a></li>
                    <li><a href="/analysis" class="text-gray-600 hover:text-primary transition-colors">数据分析</a></li>
                    <li><a href="/limitup/search" class="text-gray-600 hover:text-primary transition-colors">ZT分析</a></li>
                    <li><a href="/stocksflow" class="text-gray-600 hover:text-primary transition-colors">个股资金</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <div class="bg-white rounded-xl p-6 table-shadow mb-6 hover-scale">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold text-neutral-dark">资金流向汇总表</h2>
            <!-- 在"资金流向汇总表"标题下方添加 -->
            <div class="mb-6 bg-gray-50 p-4 rounded-lg">
                <div class="flex flex-col md:flex-row gap-4 items-start md:items-center">
                    <!-- 名称模糊查询 -->
                    <div class="flex-1 min-w-[200px]">
                        <label for="nameSearch" class="block text-sm font-medium text-gray-700 mb-1">概念名称搜索</label>
                        <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                    <i class="fa fa-search text-gray-400"></i>
                </span>
                            <input
                                    type="text"
                                    id="nameSearch"
                                    placeholder="输入概念名称关键词搜索..."
                                    class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                            >
                        </div>
                    </div>

                    <!-- 时间范围查询 -->
                    <div class="flex-1 min-w-[300px]">
                        <label class="block text-sm font-medium text-gray-700 mb-1">时间范围</label>
                        <div class="flex gap-2">
                            <input
                                    type="date"
                                    id="startDate"
                                    class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary"
                            >
                        </div>
                    </div>

                    <!-- 查询按钮 -->
                    <div class="flex items-end">
                        <button
                                id="searchBtn"
                                class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-all duration-300 flex items-center"
                        >
                            <i class="fa fa-search mr-2"></i>查询
                        </button>
                    </div>
                </div>
            </div>

            <div class="flex space-x-2">
                <button id="refreshBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center">
                    <i class="fa fa-refresh mr-2"></i>刷新数据
                </button>

            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 table-fixed-layout">
                <thead class="bg-gray-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">概念代码</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">概念名称</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day1">
                        1天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day2">
                        2天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day3">
                        3天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day4">
                        4天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day5">
                        5天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day6">
                        6天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider sortable-header" data-sort="day7">
                        7天(亿)
                        <i class="fa fa-sort sort-icon"></i>
                    </th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider " data-sort="day00">趋势</th>
                </tr>
                </thead>
                <tbody id="summaryTableBody" class="bg-white divide-y divide-gray-200">
                <!-- 表格内容将通过JavaScript动态填充 -->
                <tr class="text-center">
                    <td colspan="10" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                            <p>正在加载数据...</p>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <div id="emptyState" class="hidden text-center py-12">
            <i class="fa fa-info-circle text-4xl text-gray-400 mb-4"></i>
            <h3 class="text-xl font-medium text-gray-900 mb-2">暂无数据</h3>
            <p class="text-gray-500 max-w-md mx-auto">没有找到符合条件的概念数据，请确保数据库中有相关记录。</p>
        </div>
    </div>

    <div class="bg-white rounded-xl p-6 table-shadow hover-scale">
        <h2 class="text-xl font-semibold text-neutral-dark mb-6">数据说明</h2>
        <div class="grid md:grid-cols-2 gap-6">
            <div class="bg-blue-50 p-4 rounded-lg">
                <h3 class="font-medium text-primary mb-2 flex items-center">
                    <i class="fa fa-lightbulb-o mr-2"></i>数据含义
                </h3>
                <ul class="list-disc list-inside text-gray-700 space-y-1">
                    <li>各时间段数据为对应天数内的资金流向总和</li>
                    <li>资金流向单位为元，保留两位小数</li>
                    <li>数据按概念代码进行分组统计</li>
                    <li>点击列标题可进行排序</li>
                </ul>
            </div>
            <div class="bg-green-50 p-4 rounded-lg">
                <h3 class="font-medium text-green-700 mb-2 flex items-center">
                    <i class="fa fa-bar-chart mr-2"></i>数据分析
                </h3>
                <ul class="list-disc list-inside text-gray-700 space-y-1">
                    <li>对比不同时间段数据，可分析资金流向趋势</li>
                    <li>红色箭头表示资金流入减少趋势</li>
                    <li>绿色箭头表示资金流入增加趋势</li>
                    <li>支持按各天数列进行升序/降序排序</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<footer class="bg-neutral-dark text-white py-8 mt-12">
    <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="mb-4 md:mb-0">
                <h3 class="text-xl font-semibold mb-2">概念资金流向分析系统</h3>
                <p class="text-gray-400 text-sm">提供专业的股票概念数据分析服务</p>
            </div>
            <div class="flex space-x-6">
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-question-circle"></i> 帮助中心
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-file-text-o"></i> 使用文档
                </a>
                <a href="#" class="text-gray-400 hover:text-white transition-colors">
                    <i class="fa fa-envelope-o"></i> 联系我们
                </a>
            </div>
        </div>
        <div class="border-t border-gray-700 mt-6 pt-6 text-center text-gray-400 text-sm">
            © 2025 概念资金流向分析系统. 保留所有权利.
        </div>
    </div>
</footer>

<script>
    // 全局变量
    let currentData = [];
    let currentSortField = null;
    let currentSortDirection = 'asc';

    document.addEventListener('DOMContentLoaded', function() {
        fetchData();

        // 刷新按钮事件
        document.getElementById('refreshBtn').addEventListener('click', function() {
            fetchData(true);
        });

        // 导出按钮事件
        document.getElementById('exportBtn').addEventListener('click', function() {
            exportTableToCSV('概念资金流向汇总表.csv');
        });

        // 添加排序事件监听器
        document.querySelectorAll('.sortable-header').forEach(header => {
            header.addEventListener('click', function() {
                const sortField = this.getAttribute('data-sort');
                handleSort(sortField);
            });
        });

        document.getElementById('searchBtn').addEventListener('click', performSearch);

        // 添加名称搜索框回车事件
        document.getElementById('nameSearch').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });

        // 设置默认日期范围（例如最近7天）
        const today = new Date();
        const lastWeek = new Date();
        lastWeek.setDate(today.getDate() - 7);

        // document.getElementById('endDate').valueAsDate = today;
        document.getElementById('startDate').valueAsDate = today;
    });

    function performSearch() {
        const tableBody = document.getElementById('summaryTableBody');
        const nameSearch = document.getElementById('nameSearch').value.trim().toLowerCase();
        const startDate = document.getElementById('startDate').value;
        // const endDate = document.getElementById('endDate').value;

        // 显示加载状态
        tableBody.innerHTML = `
        <tr class="text-center">
            <td colspan="10" class="px-6 py-12 text-gray-500">
                <div class="flex flex-col items-center">
                    <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                    <p>正在查询数据...</p>
                </div>
            </td>
        </tr>
    `;

        const params = new URLSearchParams();
        params.append('nameSearch', nameSearch);
        params.append('startDate', startDate);


        // 1. 前端过滤模式（适用于数据量小的情况）
        fetch(`/gainian/summary?`+ params.toString())
            .then(response => response.json())
            .then(data => {
                // 处理数据逻辑与前端过滤模式相同
                currentData = data;
                // ...渲染数据
            })
            .catch(error => {
                console.error('查询失败:', error);
                // 错误处理
            });

        // 从原始数据过滤
        let filteredData = [...currentData];

        // 名称模糊过滤
        if (nameSearch) {
            filteredData = filteredData.filter(item =>
                item.gainianName.toLowerCase().includes(nameSearch)
            );
        }

        // 处理查询结果
        if (filteredData.length === 0) {
            tableBody.innerHTML = `
                <tr class="text-center">
                    <td colspan="10" class="px-6 py-12 text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-search text-3xl mb-3 text-gray-400"></i>
                            <p>没有找到匹配的数据</p>
                        </div>
                    </td>
                </tr>
            `;
            return;
        }

        // 应用排序并渲染结果
        if (currentSortField) {
            // 先按查询条件过滤，再应用排序
            const sortedData = [...filteredData].sort((a, b) => {
                const aValue = parseFloat(a[currentSortField]) || 0;
                const bValue = parseFloat(b[currentSortField]) || 0;
                return currentSortDirection === 'asc' ? aValue - bValue : bValue - aValue;
            });
            renderTableData(sortedData);
        } else {
            renderTableData(filteredData);
        }
    }

    // 处理排序
    function handleSort(sortField) {
        // 如果点击的是同一个字段，切换排序方向
        if (currentSortField === sortField) {
            currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            // 如果是新字段，设置为升序
            currentSortField = sortField;
            currentSortDirection = 'desc';
        }

        // 更新排序图标
        updateSortIcons(sortField, currentSortDirection);

        // 排序数据并重新渲染表格
        sortAndRenderData();
    }

    // 更新排序图标
    function updateSortIcons(activeField, direction) {
        document.querySelectorAll('.sortable-header').forEach(header => {
            const icon = header.querySelector('.sort-icon');
            const field = header.getAttribute('data-sort');

            if (field === activeField) {
                icon.className = `fa ${direction === 'asc' ? 'fa-sort-up' : 'fa-sort-down'} sort-icon active`;
            } else {
                icon.className = 'fa fa-sort sort-icon';
            }
        });
    }

    // 排序数据并重新渲染
    function sortAndRenderData() {
        if (currentData.length === 0) return;

        const sortedData = [...currentData].sort((a, b) => {
            const aValue = parseFloat(a[currentSortField]) || 0;
            const bValue = parseFloat(b[currentSortField]) || 0;

            if (currentSortDirection === 'asc') {
                return aValue - bValue;
            } else {
                return bValue - aValue;
            }
        });
        renderTableData(sortedData);
    }

    // 渲染表格数据
    function renderTableData(data) {
        const tableBody = document.getElementById('summaryTableBody');
        tableBody.innerHTML = '';

        data.forEach(item => {
            const row = document.createElement('tr');
                                row.className = 'hover:bg-gray-50 transition-colors transform-none';

            // 格式化数字
            const formatNumber = (num) => {
                if (num === null || num === undefined) return '0.00';

                // 格式化数字并保留两位小数
                const formattedValue = Number(num).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });

                // 安全转义HTML特殊字符
                const escapedValue = formattedValue
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;');

                // 根据数值正负返回相应图标
                if (Number(num) < 0) {
                    return `<i class="fa text-green-500">${escapedValue}</i>`;
                } else if (Number(num) > 0) {
                    return `<i class="text-red-500">${escapedValue}</i>`;
                }
                return escapedValue; // 处理0的情况
            };

            // 计算趋势
            const getTrendIcon = () => {
                const day1 = item.day1 || 0;
                const day2 = item.day2 || 0;
                const day3 = item.day3 || 0;

                // 这里简化判断，实际应用可以使用更复杂的算法
                if (day1 > day2 && day2 > day3) {
                    return '<i class="fa fa-arrow-up text-red-500 "></i> 上升';
                } else if (day1 < day2 && day2 < day3) {
                    return '<i class="fa fa-arrow-down text-green-500"></i> 下降';
                } else {
                    return '<i class="fa fa-minus text-gray-500"></i> 平稳';
                }
            };

            row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${item.gainianCode}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" title="${item.gainianName}">
                      ${item.gainianName.length > 10 ? item.gainianName.substring(0, 10) + '...' : item.gainianName}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">${formatNumber(item.day1/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day2/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day3/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day4/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day5/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day6/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${formatNumber(item.day7/10000/10000)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${getTrendIcon()}</td>
                `;

            tableBody.appendChild(row);
        });
    }

    // 获取并显示数据
    function fetchData(showLoading = false) {
        const tableBody = document.getElementById('summaryTableBody');
        const emptyState = document.getElementById('emptyState');

        const today = new Date();
        document.getElementById('startDate').valueAsDate = today;
        document.getElementById('nameSearch').value = "";

        if (showLoading) {
            tableBody.innerHTML = `
                    <tr class="text-center">
                        <td colspan="9" class="px-6 py-12 text-gray-500">
                            <div class="flex flex-col items-center">
                                <i class="fa fa-spinner fa-spin text-3xl mb-3 text-primary"></i>
                                <p>正在刷新数据...</p>
                            </div>
                        </td>
                    </tr>
                `;
            emptyState.classList.add('hidden');
        }


        // 模拟API调用
        // 实际环境中请替换为真实API地址
        fetch('/gainian/summary')
            .then(response => response.json())
            .then(data => {
                if (data.length === 0) {
                    tableBody.innerHTML = '';
                    emptyState.classList.remove('hidden');
                    return;
                }

                emptyState.classList.add('hidden');

                // 保存数据到全局变量
                currentData = data;

                // 如果有当前排序设置，应用排序
                if (currentSortField) {
                    sortAndRenderData();
                } else {
                    renderTableData(data);
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                tableBody.innerHTML = `
                        <tr class="text-center">
                            <td colspan="9" class="px-6 py-12 text-red-500">
                                <div class="flex flex-col items-center">
                                    <i class="fa fa-exclamation-triangle text-3xl mb-3"></i>
                                    <p>加载数据失败，请稍后重试</p>
                                </div>
                            </td>
                        </tr>
                    `;
            });
    }

    // 导出表格为CSV
    function exportTableToCSV(filename) {
        const tableData = [];
        const headers = ['概念代码', '概念名称', '7天汇总(元)', '6天汇总(元)', '5天汇总(元)', '3天汇总(元)', '2天汇总(元)', '1天汇总(元)', '趋势'];

        tableData.push(headers.join(','));

        const rows = document.querySelectorAll('#summaryTableBody tr');
        rows.forEach(row => {
            if (row.querySelector('td[colspan="9"]')) return; // 跳过加载/错误信息行

            const rowData = [];
            const cells = row.querySelectorAll('td');
            cells.forEach(cell => {
                // 移除HTML标签，只保留文本内容
                let text = cell.textContent || cell.innerText;
                // 替换逗号，避免CSV格式错误
                text = text.replace(/,/g, '，');
                rowData.push(`"${text}"`);
            });
            tableData.push(rowData.join(','));
        });

        // 创建CSV文件并下载
        const csvContent = tableData.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
</body>
</html>